/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import Connectdata.connectdatabase;
import DTO.Object.OrderDetail.Orderdetail1;
import DTO.Object.OrderDetail.Orderdetails;
import DTO.Object.OrderUser.Orderuser1;
import DTO.Object.OrderUser.Orderusers;
import DTO.Object.Users.UserSchema1;
import DTO.Object.Users.UserSchemas;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

/**
 *
 * @author annt60258
 */
public class PrintOrderHistory extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            HttpSession session = request.getSession();
            String idorder = request.getParameter("idorder");
            connectdatabase con = new connectdatabase();
            con.connect();
            double tong =0;
            String realpath = getServletContext().getRealPath("/");
            String path_orderuser = realpath+"XML/Orderxml.xml";
            String path_userschema = realpath+"XML/Userxml.xml";
            String path_orderdetail = realpath+"XML/Orderdetailxml.xml";

            Orderusers orderusers = new Orderusers();
            Orderuser1 orderuser1 = new Orderuser1();
            con.connectstring("select * from OrderPayment where orderStatus<2 and orderID=" + idorder);
            con.rs_connect.next();
            orderuser1.setUserName(con.rs_connect.getString("userName"));
            String datbuy = con.rs_connect.getDate("orderDate")+"T"+con.rs_connect.getTime("orderDate");
            XMLGregorianCalendar xmldate = DatatypeFactory.newInstance().newXMLGregorianCalendar(datbuy);
            orderuser1.setOrderDate(xmldate);
            orderusers.getOrderuser().add(orderuser1);
            JAXBContext jaxb_orderuser = JAXBContext.newInstance(orderusers.getClass());
            Marshaller mar_orderuser = jaxb_orderuser.createMarshaller();
            mar_orderuser.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
            mar_orderuser.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
            mar_orderuser.marshal(orderusers, new File(path_orderuser));

            UserSchemas userschemas = new UserSchemas();
            UserSchema1 userschema1 = new UserSchema1();
            con.connectstring("select * from UserAccount where userName='"+con.rs_connect.getString("userName")+"'");
            con.rs_connect.next();
            userschema1.setFullName(con.rs_connect.getString("FullName"));
            userschema1.setEmail(con.rs_connect.getString("Mail"));
            userschema1.setPhone(con.rs_connect.getString("Phone"));
            userschema1.setAddress(con.rs_connect.getString("Address"));
            userschemas.getUserSchema().add(userschema1);
            JAXBContext jaxb_userschema = JAXBContext.newInstance(userschemas.getClass());
            Marshaller mar_userschema = jaxb_userschema.createMarshaller();
            mar_userschema.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar_userschema.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar_userschema.marshal(userschemas, new File(path_userschema));

            Orderdetails orderdetails = new Orderdetails();
            
            con.connectstring("select * from OrderDetail where orderMother="+idorder);
            while(con.rs_connect.next())
            {
                Orderdetail1 orderdetail1 = new Orderdetail1();
                int proid = con.rs_connect.getInt("proID");
                orderdetail1.setQuantity(Long.valueOf(con.rs_connect.getInt("quantity")));
                orderdetail1.setPrice(BigInteger.valueOf(con.rs_connect.getLong("priceProduct")));
                tong=tong+con.rs_connect.getLong("priceProduct")*con.rs_connect.getInt("quantity");
                connectdatabase conn = new connectdatabase();
                conn.connect();
                conn.connectstring("select * from Product where proID="+proid);
                conn.rs_connect.next();
                orderdetail1.setProductName(conn.rs_connect.getString("proName"));
                orderdetail1.setPicture(realpath+conn.rs_connect.getString("Image"));

                orderdetails.getOrderdetail().add(orderdetail1);
            }
            orderdetails.setTong((int)tong);
            JAXBContext jaxb_orderdetail = JAXBContext.newInstance(orderdetails.getClass());
            Marshaller mar_orderdetail = jaxb_orderdetail.createMarshaller();
            mar_orderdetail.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar_orderdetail.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar_orderdetail.marshal(orderdetails, new File(path_orderdetail));


            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer(new StreamSource(realpath+"xsl/PDF_FO.xsl"));
            tf.transform(new StreamSource(path_userschema),new StreamResult(new FileOutputStream(realpath+"WEB-INF/Furniture.fo")));

            FileInputStream input = new FileInputStream(new File(realpath+"WEB-INF/Furniture.fo"));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            response.setContentType("application/pdf");
            Driver driver = new Driver(new InputSource(input),output);
            driver.setRenderer(Driver.RENDER_PDF);
            driver.run();
            byte[] content = output.toByteArray();
            response.setContentLength(content.length);
            response.getOutputStream().write(content);
            response.getOutputStream().flush();
            


        } catch (FOPException ex) {
            Logger.getLogger(PrintOrderHistory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(PrintOrderHistory.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (JAXBException ex) {
            Logger.getLogger(PrintOrderHistory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(PrintOrderHistory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(PrintOrderHistory.class.getName()).log(Level.SEVERE, null, ex);
        }

        
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
